<!-- 选择用户弹窗 -->
<template>
  <div>
    <el-dialog v-model="dialogVisible" title="选择用户" width="1100">
      <div class="select-user-mask">
        <div style="width: 300px; margin-right: 15px">
          <el-scrollbar max-height="585px">
            <el-tree
              ref="serveTree"
              :props="treeProps"
              node-key="orgNo"
              :default-expanded-keys="defaultExpandedKeys"
              :load="loadNode"
              lazy
              :expand-on-click-node="false"
              @node-click="clickNode"
            />
          </el-scrollbar>
        </div>
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            row-key="userId"
            :tool-button="false"
            height="535"
          >
            <template #tableHeader="scope">
              <div v-if="scope">
                <el-form :inline="true">
                  <el-form-item label="角色">
                    <el-select v-model="roleNo" placeholder="请选择角色" style="width: 200px" clearable>
                      <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="登录名">
                    <el-input v-model="loginName" style="width: 200px" clearable />
                  </el-form-item>
                  <el-form-item label="">
                    <el-button type="primary" style="margin: 0" @click="search">搜索</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </template>
            <template #userState="scope">
              <div>
                <span v-if="scope.row.userState">值班中</span>
                <span v-else>休假中</span>
              </div>
            </template>
            <template #operation="scope">
              <div>
                <el-button type="primary" plain v-if="scope.row.userState" @click="selectUser(scope.row)">选择</el-button>
              </div>
            </template>
          </ProTable>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="SelectUserMask">
import { ref, computed, watch } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { findAllOrganization, findUserList } from "@/api/modules/common";
import { getRoleList } from "@/api/modules/user";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance } from "@/components/ProTable/interface";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();

interface Tree {
  orgNo: string;
  orgName: string;
  orgType: string;
  children?: Tree[];
}

const treeProps = {
  label: "orgName",
  children: "children",
  isLeaf: "leaf"
};

const defaultExpandedKeys = ref<string[]>(["1"]);

const loadNode = (node: Node, resolve: (data: Tree[]) => void, reject: () => void) => {
  if (node.level === 0) {
    loading.value = true;
    findAllOrganization({
      companyNo: userStore.userInfo.companyNo,
      parentOrgNo: 0,
      _: new Date().getTime()
    })
      .then((res: any) => {
        loading.value = false;
        let list = res.map(element => {
          return {
            ...element.attr,
            children: element.children
          };
        });
        resolve(list);
      })
      .catch(() => {
        loading.value = false;
        reject();
      });
  } else if (node.level === 1) {
    let arr1 = node.data.children || [];
    let list = ref<Tree[]>([]);
    arr1.forEach(item => {
      list.value.push({
        ...item.attr,
        children: item.children,
        leaf: item.state ? false : true
      });
    });
    resolve(list.value);
  } else if (node.level === 2) {
    let arr2 = node.data.children || [];
    let list2 = ref<Tree[]>([]);
    arr2.forEach(item => {
      list2.value.push({
        ...item.attr,
        children: item.children,
        leaf: item.state ? false : true
      });
    });
    resolve(list2.value);
  } else {
    findAllOrganization({
      companyNo: userStore.userInfo.companyNo,
      parentOrgNo: node.data.orgNo,
      _: new Date().getTime()
    })
      .then((res: any) => {
        let list = res.map(element => {
          return {
            ...element.attr,
            children: element.children,
            leaf: element.state ? false : true
          };
        });
        resolve(list);
      })
      .catch(() => {
        reject();
      });
  }
};

const clickNode = (e: any) => {
  if (e.orgNo == orgNo.value) return;
  orgNo.value = e.orgNo;
  orgType.value = "";
  proTable.value?.getTableList();
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

const props = defineProps({
  title: {
    type: String,
    default: "机构"
  },
  groupNo: {
    type: [Number, String],
    default: 0
  }
});

watch(
  () => props.groupNo,
  val => {
    proTable.value?.getTableList();
  }
);

const orgNo = ref(0);
const orgType = ref("");
const roleNo = ref(0);
const loginName = ref("");

// 表格配置项
const columns = computed(() => {
  return [
    { prop: "loginName", label: "登录名" },
    { prop: "fullName", label: "名字" },
    { prop: "email", label: "邮箱" },
    { prop: "userState", label: "休假状态", width: "130" },
    { prop: "operation", label: "操作", width: "130" }
  ];
});

const loading = ref(false);
const isRefresh = ref(false);

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
const getTableList = (params: any) => {
  loading.value = true;
  let page = params.pageNum;
  if (isRefresh.value) {
    page = 1;
    isRefresh.value = false;
  }
  return findUserList({
    "userQueryDto.companyNo": userStore.userInfo.companyNo,
    "userQueryDto.roleNo": roleNo.value, // 角色
    "userQueryDto.loginName": loginName.value, // 登录名
    "userQueryDto.orgNo": props.groupNo || orgNo.value,
    "userQueryDto.orgType": orgType.value,
    state: true,
    _search: false,
    nd: new Date().getTime(),
    sidx: "userId",
    sord: "desc",
    page: page,
    rows: params.pageSize
  }).catch(() => {
    loading.value = false;
  });
};

// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  loading.value = false;
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const search = () => {
  proTable.value?.getTableList();
};

// 定义用户接口
interface User {
  userId: number;
  loginName: string;
  fullName: string;
  email: string;
}

// 定义 emit 事件，使用 User 类型作为 change 事件的参数
const emit = defineEmits<{
  (e: "change", user: User): void;
}>();

// 选择用户
const selectUser = (user: User) => {
  dialogVisible.value = false;
  emit("change", user);
};

const dialogVisible = ref(false);

const roleList = ref<any[]>([]);

const open = () => {
  dialogVisible.value = true;
  isRefresh.value = true;
  orgNo.value = 0;

  if (roleList.value.length == 0) {
    getRoleList().then((res: any) => {
      let list = ref<any[]>([
        {
          label: "全部",
          value: 0
        }
      ]);
      res.data.forEach(element => {
        list.value.push({
          label: element.roleName,
          value: element.roleId
        });
      });

      roleList.value = list.value;
    });
  }
};

defineExpose({
  open
});
</script>

<style lang="scss" scoped>
:deep(.card) {
  padding: 0;
  border: none;
  box-shadow: none;
}
.select-user-mask {
  display: flex;
}
:deep(.el-tree-node:focus > .el-tree-node__content) {
  color: #ffffff;
  background-color: var(--el-color-primary);
}
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  color: #ffffff;
  background-color: var(--el-color-primary);
}
</style>
